﻿using CommonExtenControl;
using CommonExtenControl.Enum;
using CommonExtenControl.Model;
using CustomControls.PoptipCtr;
using ManagementTool.BaseViewModels;
using ManagementTool.Config;
using ManagementTool.DB.Control;
using ManagementTool.DB.Model;
using ManagementTool.DB.Sql;
using ManagementTool.NetWorks;
using ManagementTool.PageDeclaration;
using Microsoft.Win32;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using static System.Net.Mime.MediaTypeNames;

namespace ManagementTool.ViewModels
{
    public class IndexPageViewModel : BaseViewModel
    {
        private Dictionary<int, int> CurrentItemIndex { set; get; }

        #region UIProperty
        private CommonExtenControl.Model.DeviceModel _SelectDeviceModel;

        public CommonExtenControl.Model.DeviceModel SelectDeviceModel
        {
            get { return _SelectDeviceModel; }
            set { SetProperty(ref _SelectDeviceModel, value); }
        }

        private bool _IsHandSearch = false;

        public bool IsHandSearch
        {
            get
            {
                return _IsHandSearch;
            }
            set
            {
                SetProperty(ref _IsHandSearch, value);
            }
        }

        private ObservableCollection<CommonExtenControl.Model.DeviceModel> _DeviceList;

        public ObservableCollection<CommonExtenControl.Model.DeviceModel> DeviceList
        {
            get { return _DeviceList; }
            set { SetProperty(ref _DeviceList, value); }
        }

        #endregion

        #region cmd
        private DelegateCommand<int?> _PageUpdatedCommand;
        public DelegateCommand<int?> PageUpdatedCommand =>
            _PageUpdatedCommand ?? (_PageUpdatedCommand = new DelegateCommand<int?>(ExecutePageUpdatedCommand));


        private DelegateCommand _MaintenanceCommand;
        public DelegateCommand MaintenanceCommand =>
            _MaintenanceCommand ?? (_MaintenanceCommand = new DelegateCommand(MaintenanceCommandMethod));


        private DelegateCommand _RefreshCommand;
        public DelegateCommand RefreshCommand =>
            _RefreshCommand ?? (_RefreshCommand = new DelegateCommand(RefreshCommandMethod));


        private DelegateCommand _UpdateCommand;
        public DelegateCommand UpdateCommand =>
            _UpdateCommand ?? (_UpdateCommand = new DelegateCommand(UpdateCommandMethod));

        private DelegateCommand _QuitCommand;
        public DelegateCommand QuitCommand =>
            _QuitCommand ?? (_QuitCommand = new DelegateCommand(QuitCommandMethod));

        private DelegateCommand _RuntCommand;
        public DelegateCommand RuntCommand =>
            _RuntCommand ?? (_RuntCommand = new DelegateCommand(RunCommandMethod));


        private DelegateCommand _UpLoadCommand;
        public DelegateCommand UpLoadCommand =>
            _UpLoadCommand ?? (_UpLoadCommand = new DelegateCommand(UpLoadCommandMethod));

   


        #endregion


        public IndexPageViewModel(IContainerExtension container) : base(container)
        {

        }


        private async void ExecutePageUpdatedCommand(int? JumpIndex)
        {
            await Task.Run(() => {
                GetDevListFromDB(JumpIndex.Value); 
            });
        }

        private void MaintenanceCommandMethod()
        {
            if (this.SelectDeviceModel == null)
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
        }


        private void RefreshCommandMethod()
        {
            Task.Run(() => {
                GetAllCount();
                GetDevListFromDB(1);
            });
        }


        private void UpdateCommandMethod()
        {
            if (this.SelectDeviceModel==null) 
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
            ShowDialog(SystemResourceExten.Nav_FileSelectPageView);
        }
        private void ShowDialog(string _PageView)
        { 
            DialogParameters dialogParameters = new DialogParameters();

            this.Dialog?.Show(_PageView, dialogParameters, DoDialogResult);
        }

        private void DoDialogResult(IDialogResult objDResult)
        {
            try
            {
                if (objDResult.Result == ButtonResult.OK)
                {
                    string _fileName = "";
                    string _filePath = "";
                    string _fileVersion = "";
                    if (objDResult.Parameters.ContainsKey("FileName"))
                    {
                        _fileName = objDResult.Parameters.GetValue<string>("FileName");
                    }
                    if (objDResult.Parameters.ContainsKey("FilePath"))
                    {
                        _filePath = objDResult.Parameters.GetValue<string>("FilePath");
                    }
                    if (objDResult.Parameters.ContainsKey("FileVersion"))
                    {
                        _fileVersion = objDResult.Parameters.GetValue<string>("FileVersion");
                    }


                }
                else if (objDResult.Result == ButtonResult.Retry)
                {
                    MessageControl.Warning("请选择行!", SystemResourceExten.Nav_RootMessageTooken);
                }
            }
            catch (Exception ex)
            {
               
            }
        }

        private void QuitCommandMethod()
        {
            if (this.SelectDeviceModel == null)
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }

            //int _Type = GetCurrentOperationTypeToInt(this.SelectDeviceModel.CurrentOperationType);
            //string _sql = InstanceBase<SqlsControl>.Instance.GetUpdateDevCurrentOperationTypeSql(this.SelectDeviceModel.PcSign, _Type);
            //int resultUpdate = InstanceBase<MySqlDbControl>.Instance.ExeCuteCommonSql(_sql);
            //string MesgTip = resultUpdate == -1 ? "操作失败" : "操作成功";

            //var itemModel = new CommonExtenControl.Model.DeviceModel();
            //itemModel.RecvDataTypeModel = "DeviceDate";
            //itemModel.CurrentOperationType = OperationType.Stop;
            //string strMsg=JsonConvert.SerializeObject(itemModel);
           // InstanceBase<SocketControl>.Instance.SendMsg(this.SelectDeviceModel.IPAddress, strMsg,0);
        }

        private int GetCurrentOperationTypeToInt(OperationType itemType) 
        {
            int _Type = 5;
            switch (itemType)
            {
                case OperationType.Maintenance:
                    _Type = 1;
                    break;
                case OperationType.Update:
                    _Type = 2;
                    break;
                case OperationType.Stop:
                    _Type = 3;
                    break;
                case OperationType.Run:
                    _Type = 4;
                    break;
                case OperationType.Other:
                    _Type = 5;
                    break;
            }
            return _Type;
        }

        private void RunCommandMethod()
        {
            if (this.SelectDeviceModel == null)
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
        }


        private void UpLoadCommandMethod()
        {
            if (this.SelectDeviceModel == null)
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
            InstanceBase<ClientNetWorkControl>.Instance.ToSendFile();
        }
        public override void ExecuteLoadedCommand()
        {
            base.ExecuteLoadedCommand();
            CurrentItemIndex = new Dictionary<int, int>();
            DeviceList = new ObservableCollection<CommonExtenControl.Model.DeviceModel>();
            Task.Run(() => {
                GetAllCount();
                GetDevListFromDB(1);
            });
        }

        public override void ExecuteUnLoadedCommand()
        {
            base.ExecuteUnLoadedCommand();
        }

 
        private void GetAllCount() 
        {
            string _AllCountSql = InstanceBase<SqlsControl>.Instance.GetDeviceInfoDBCountSql();
            PageCount = InitDate(_AllCountSql);
            PageItemsCount = Limits.FirstOrDefault();
        }

        private void GetDevListFromDB(int _currentPageIndex)
        {
            try
            {
                string _str_sql = InstanceBase<SqlsControl>.Instance.GetDeviceInfoDBSql(_currentPageIndex, PageItemsCount);
                var _dataSet = InstanceBase<MySqlDbControl>.Instance.ExecuteQuery(_str_sql);
                int SumIndex = GetSumIndex(1);
                IList<DeviceInfo> resultList = ModelConvertHelper<DeviceInfo>.ConvertToModel(_dataSet);

                if (resultList.Count > 0)
                {
                    System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                        DeviceList.Clear();
                        foreach (var item in resultList)
                        {
                            SumIndex++;
                            var itemModel = new CommonExtenControl.Model.DeviceModel();
                            itemModel.Index = SumIndex;
                            itemModel.EffectTime = item.effecttime;
                            itemModel.MacInfo = item.macinfo;
                            itemModel.CurrentVersion = item.version;
                            itemModel.DescripMsg = item.descripmsg;
                            DeviceList.Add(itemModel);  
                        }
                    }));
                }
            }
            catch (Exception ex) 
            {
              
            }
        }

        private OperationType GetOperationType(int _CurrentOperationType) 
        {
            OperationType item = OperationType.Other;
            if (_CurrentOperationType == 1)
            {
                item = OperationType.Update;
            } 
            else if (_CurrentOperationType == 2)
            {
                item = OperationType.Stop;
            }
            else if (_CurrentOperationType == 3)
            {
                item = OperationType.Run;
            }
            else if (_CurrentOperationType == 4)
            {
                item = OperationType.Other;
            }
            return item;
        }

        private OperationResultType GetCurrentOperationResultTypee(int _CurrentOperationType)
        {
            OperationResultType item = OperationResultType.Other;
            if (_CurrentOperationType == 1)
            {
                item = OperationResultType.Success;
            }
            else if (_CurrentOperationType == 2)
            {
                item = OperationResultType.Error;
            }
            else if (_CurrentOperationType == 3)
            {
                item = OperationResultType.Other;
            }

            return item;
        }

        protected virtual int GetSumIndex(int _pageIndex)
        {
            int sum = 0;
            int _SumIndex = 0;
            try
            {
                CurrentItemIndex.Clear();
                int sumCunt = SumPageCount / PageItemsCount + 1;
                for (int i = 1; i <= sumCunt; i++)
                {
                    CurrentItemIndex.Add(i, _SumIndex);
                    _SumIndex += PageItemsCount;
                }


                if (CurrentItemIndex.Count > 0)
                {
                    sum = CurrentItemIndex[_pageIndex];
                }
            }
            catch (Exception ex)
            {
               
            }
            return sum;
        }
    }
}
